import { Bus, CONN_ACTIVITY, CONN_CHAIN_CLEVER } from "./Bus";
import { onDatas } from "./tooler";

const chain = { event: "subscribe", group: "ALL", topic: "on_chain" };
const url = "wss://api.chainingview.io/chain-websocket";
const api = "https://api.chainingview.io/api/chain-stream/activity/list?group=BIG_AMOUNT";
const compressed = true;

export function initConn() {

    let socket = new WebSocket(url);
    socket.onopen = ev => {
        console.warn("链接成功 ====", socket.readyState, ev);
        socket.send(JSON.stringify(chain));
        setInterval(() => {
            socket.send("ping");
        }, 10000)
    }
    socket.onmessage = async (ev) => {
        var data = ev.data;
        if (compressed) {
            data = await onDatas(data);
        }

        if (data == "pong") {
            return;
        }

        var jsondata = JSON.parse(data);
        handle(jsondata);
    };

    setTimeout(loadData, 300);
}

function loadData() {
    fetch(api)  // 替换为你要请求的URL
        .then(response => response.json())
        .then(data => {
            // 处理获取到的JSON数据
            console.log(data);
            Bus.emit(CONN_ACTIVITY, data.data);
        })
        .catch(error => {
            // 处理请求错误
            console.error(error);
        });
}

function handle(jsondata: any): void {
    // console.log(jsondata)
    if (!jsondata.data) return;
    // if( jsondata.data.type == "swap" && (jsondata.data.outAmount || jsondata.data.inAmount )){
    //     return;
    // }

    switch (jsondata.group) {
        case "CAPITAL_ABNORMAL":
            if (jsondata.data.type !== "cex") {
                Bus.emit(CONN_CHAIN_CLEVER, jsondata.data);
            }
            break;
        case "ALL":
            Bus.emit(CONN_ACTIVITY, jsondata.data);
            break;
    }
}